package com.ysqcould.mp.utils;

import cn.hutool.core.util.ObjectUtil;
import com.ysqcould.common.utils.http.HttpUtils;
import com.ysqcould.common.utils.spring.SpringUtils;
import com.ysqcould.content.domain.Press;
import com.ysqcould.content.mapper.PressMapper;
import com.ysqcould.mp.service.IMpArticleService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

import static com.ysqcould.common.oss.OssClientUtil.uploadUrlImage;

/**
 * 解析文章工具类
 * @author jcd
 */
public class ParsingArticleUtil<T> {
    /**
     * 通过url解析文章内容
     * @param url
     */
    public static Press parsingArticles(String url){
        PressMapper pressMapper = SpringUtils.getBean(PressMapper.class);
        Press press=new Press();

        final String s = get(url,getWxHeaderMap());
        final Document doc = Jsoup.parse(s);
        /**文章内容**/
        final String content = doc.getElementById("js_content").html();
        if (ObjectUtil.isNotEmpty(content)){
            /**文章标题**/
            final String title = doc.select("meta[property=\"twitter:title\"]").attr("content");
            /**文章标签**/
            final String tag = doc.select("meta[property=\"og:description\"]").attr("content");
            /**文章封面**/
            final String coverUrl = doc.select("meta[property=\"twitter:image\"]").attr("content");
            /**已上传文章封面**/
            final String urlImage = uploadUrlImage(coverUrl);
            final Elements img = doc.select("img");
            List<String> imgList=new ArrayList<>();
            Map<String,String> map=new HashMap<>();
            for (Element element : img) {
                final String  imageUrl = element.attr("data-src");
                if (ObjectUtil.isNotEmpty(imageUrl)){
                    final String image = uploadUrlImage(imageUrl);
                   map.put(imageUrl,image);
                }
            }
            StringBuffer replaceContent=null;
            if (ObjectUtil.isNotEmpty(map)){
                final Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
                while (it.hasNext()){
                    final Map.Entry<String, String> entry = it.next();
                    replaceContent = ObjectUtil.isEmpty(replaceContent) ? new StringBuffer(content):replaceContent;
                    replaceContent = new StringBuffer(ObjectUtil.isEmpty(replaceContent)?"":replaceContent.toString().replace(entry.getKey(), (entry.getValue())));
                }
                final String replace = replaceContent.toString().replace("data-src", "src");
                press.setPcUrl(urlImage);
                press.setContent(replace);
                press.setTag(tag);
                press.setName(title);
            }
        }
        return press;
    }
    public static Map<String, String> getWxHeaderMap() {
        Map<String, String> map = new HashMap<>(new LinkedHashMap<>());
        map.put("Accept", "text/html, application/xhtml+xml, image/jxr, */*");
        map.put("Accept-Encoding", "gzip, deflate");
        map.put("Accept-Language", "zh-Hans-CN, zh-Hans; q=0.8, en-US; q=0.5, en; q=0.3");
        map.put("Host", "mp.weixin.qq.com");
        map.put("If-Modified-Since", "Sat, 04 Jan 2020 12:23:43 GMT");
        map.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
        return map;
    }

    /**
     * get请求
     * @param url 请求地址（get请求时参数自己组装到url上）
     * @param headerMap 请求头
     * @return 响应文本
     */
    public static String get(String url, Map<String, String> headerMap) {
        // 请求地址，以及参数设置
        HttpGet get = new HttpGet(url);
        if (headerMap != null) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                get.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // 执行请求，获取相应
        return getRespString(get);
    }

    /**
     * 获取响应信息（String）
     */
    public static String getRespString(HttpUriRequest request) {
        // 获取响应流
        InputStream in = getRespInputStream(request);

        StringBuilder sb = new StringBuilder();
        String line;

        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String str = sb.toString();
        return str;
    }
    /**
     * 获取响应信息（InputStream）
     */
    public static InputStream getRespInputStream(HttpUriRequest request) {
        // 获取响应对象
        HttpResponse response = null;
        try {
            response = HttpClients.createDefault().execute(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (response == null) {
            return null;
        }
        // 获取Entity对象
        HttpEntity entity = response.getEntity();
        // 获取响应信息流
        InputStream in = null;
        if (entity != null) {
            try {
                in =  entity.getContent();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return in;
    }

}
